const { query, withTransaction } = require("../utils/db");
const { v4: uuidv4 } = require("uuid");

/**
 * =========================
 * 角色管理
 * =========================
 */

// 获取角色列表
exports.getRoleList = async ({ page = 1, pageSize = 10, search }) => {
  const offset = (page - 1) * pageSize;
  let sql = "SELECT * FROM t_roles";
  let countSql = "SELECT COUNT(*) as total FROM t_roles";
  let params = [];
  let countParams = [];

  if (search) {
    const searchParam = `%${search}%`;
    sql += " WHERE FName LIKE ? OR FCode LIKE ?";
    countSql += " WHERE FName LIKE ? OR FCode LIKE ?";
    params = [searchParam, searchParam];
    countParams = [searchParam, searchParam];
  }

  sql += " LIMIT ? OFFSET ?";
  params = params.concat([parseInt(pageSize), parseInt(offset)]);

  const rows = await query(sql, params);
  const [totalResult] = await query(countSql, countParams);

  return {
    list: rows,
    total: totalResult.total,
    page: parseInt(page),
    pageSize: parseInt(pageSize),
  };
};
// 获取所有角色
exports.getRoleAll = async () => {
  let sql = "SELECT * FROM t_roles";
  const rows = await query(sql);
  return rows;
};

// 获取角色详情
exports.getRoleById = async ({ id }) => {
  const roles = await query("SELECT * FROM t_roles WHERE FId = ? LIMIT 1", [
    id,
  ]);
  if (roles.length === 0) {
    throw { status: 500, message: "角色不存在" };
  }

  const permissions = await query(
    `SELECT p.FId, p.FName, p.FCode 
     FROM t_permissions p
     JOIN t_role_permissions rp ON p.FId = rp.FPermissionId
     WHERE rp.FRoleId = ?`,
    [id]
  );

  return {
    ...roles[0],
    permissions,
  };
};

// 创建角色
exports.createRole = async ({ FName, FCode, FDescription = "" }) => {
  const existing = await query(
    "SELECT FId FROM t_roles WHERE FCode = ? LIMIT 1",
    [FCode]
  );
  if (existing.length > 0) {
    throw { status: 400, message: "角色编码已存在" };
  }

  const FRoleId = uuidv4();
  await query(
    "INSERT INTO t_roles (FId, FName, FCode, FDescription) VALUES (?, ?, ?, ?)",
    [FRoleId, FName, FCode, FDescription]
  );

  return { FRoleId, FName, FCode, FDescription };
};

// 更新角色
exports.updateRole = async ({ id, FName, FCode, FDescription }) => {
  const existing = await query(
    "SELECT FId FROM t_roles WHERE FId = ? LIMIT 1",
    [id]
  );
  if (existing.length === 0) {
    throw { status: 500, message: "角色不存在" };
  }

  if (FCode) {
    const conflict = await query(
      "SELECT FId FROM t_roles WHERE FCode = ? AND FId != ? LIMIT 1",
      [FCode, id]
    );
    if (conflict.length > 0) {
      throw { status: 400, message: "角色编码已存在" };
    }
  }

  const updates = [];
  const params = [];
  if (FName !== undefined) {
    updates.push("FName = ?");
    params.push(FName);
  }
  if (FCode !== undefined) {
    updates.push("FCode = ?");
    params.push(FCode);
  }
  if (FDescription !== undefined) {
    updates.push("FDescription = ?");
    params.push(FDescription);
  }

  if (updates.length === 0) {
    throw { status: 400, message: "无更新内容" };
  }

  params.push(id);
  const result = await query(
    `UPDATE t_roles SET ${updates.join(", ")} WHERE FId = ?`,
    params
  );

  return result.affectedRows > 0;
};

// 删除角色（事务版）
exports.deleteRole = async ({ id }) => {
  return withTransaction(async (conn) => {
    const users = await query(
      "SELECT FUserId FROM t_user_roles WHERE FRoleId = ? LIMIT 1",
      [id],
      conn
    );
    if (users.length > 0) {
      throw { status: 400, message: "该角色下仍有用户，无法删除" };
    }

    await query("DELETE FROM t_role_permissions WHERE FRoleId = ?", [id], conn);
    const result = await query("DELETE FROM t_roles WHERE FId = ?", [id], conn);
    if (result.affectedRows === 0) {
      throw { status: 500, message: "角色不存在" };
    }

    return true;
  });
};

/**
 * =========================
 * 权限管理
 * =========================
 */

/**
 * =========================
 * 权限模块分类管理
 * =========================
 */
// 获取权限模块列表
exports.getPermissionModules = async () => {
  return await query(
    "SELECT FId, FId as id, FName, FCode, FDescription, FOrderNum FROM t_permission_modules ORDER BY FOrderNum"
  );
};

// 创建权限模块分类
exports.createPermissionModule = async ({
  FName,
  FCode,
  FDescription = "",
  FOrderNum = 0,
}) => {
  // 检查编码是否已存在
  const existing = await query(
    "SELECT FId FROM t_permission_modules WHERE FCode = ? LIMIT 1",
    [FCode]
  );
  if (existing.length > 0) {
    throw { status: 400, message: "模块编码已存在" };
  }

  const FId = uuidv4();
  await query(
    "INSERT INTO t_permission_modules (FId, FName, FCode, FDescription, FOrderNum) VALUES (?, ?, ?, ?, ?)",
    [FId, FName, FCode, FDescription, FOrderNum]
  );

  return { FId, FName, FCode, FDescription, FOrderNum };
};

// 更新权限模块分类
exports.updatePermissionModule = async ({
  id,
  FName,
  FCode,
  FDescription,
  FOrderNum,
}) => {
  const existing = await query(
    "SELECT FId FROM t_permission_modules WHERE FId = ? LIMIT 1",
    [id]
  );
  if (existing.length === 0) {
    throw { status: 400, message: "模块分类不存在" };
  }

  // 检查编码冲突
  if (FCode) {
    const conflict = await query(
      "SELECT FId FROM t_permission_modules WHERE FCode = ? AND FId != ? LIMIT 1",
      [FCode, id]
    );
    if (conflict.length > 0) {
      throw { status: 400, message: "模块编码已存在" };
    }
  }

  const updates = [];
  const params = [];
  if (FName !== undefined) {
    updates.push("FName = ?");
    params.push(FName);
  }
  if (FCode !== undefined) {
    updates.push("FCode = ?");
    params.push(FCode);
  }
  if (FDescription !== undefined) {
    updates.push("FDescription = ?");
    params.push(FDescription);
  }
  if (FOrderNum !== undefined) {
    updates.push("FOrderNum = ?");
    params.push(FOrderNum);
  }

  if (updates.length === 0) {
    throw { status: 400, message: "无更新内容" };
  }

  params.push(id);
  const result = await query(
    `UPDATE t_permission_modules SET ${updates.join(", ")} WHERE FId = ?`,
    params
  );

  return result.affectedRows > 0;
};

// 删除权限模块分类（事务版）
exports.deletePermissionModule = async (id) => {
  return withTransaction(async (conn) => {
    // 检查是否有权限关联该模块
    const permissions = await query(
      "SELECT FId FROM t_permissions WHERE FModuleId = ? LIMIT 1",
      [id],
      conn
    );

    if (permissions.length > 0) {
      throw { status: 400, message: "该模块下仍有权限，无法删除" };
    }

    const result = await query(
      "DELETE FROM t_permission_modules WHERE FId = ?",
      [id],
      conn
    );

    if (result.affectedRows === 0) {
      throw { status: 400, message: "模块分类不存在" };
    }

    return true;
  });
};

// 获取权限模块详情
exports.getPermissionModuleById = async (id) => {
  const modules = await query(
    "SELECT * FROM t_permission_modules WHERE FId = ? LIMIT 1",
    [id]
  );
  if (modules.length === 0) {
    throw { status: 400, message: "模块分类不存在" };
  }
  return modules[0];
};
exports.getPermissionList = async (params = {}) => {
  let sql = `
    SELECT 
      p.*,
      m.FName as FModuleName,
      m.FCode as FModuleCode
    FROM t_permissions p
    LEFT JOIN t_permission_modules m ON p.FModuleId = m.FId
  `;

  const whereClauses = [];
  const queryParams = [];

  // 添加权限名称查询条件
  if (params.FName) {
    whereClauses.push("p.FName LIKE ?");
    queryParams.push(`%${params.FName}%`);
  }

  // 添加模块ID查询条件
  if (params.FModuleId) {
    whereClauses.push("p.FModuleId = ?");
    queryParams.push(params.FModuleId);
  }

  // 如果有查询条件，添加 WHERE 子句
  if (whereClauses.length > 0) {
    sql += " WHERE " + whereClauses.join(" AND ");
  }

  // 添加排序
  sql += " ORDER BY m.FOrderNum, p.FCode";

  return await query(sql, queryParams);
};

exports.createPermission = async ({
  FName,
  FCode,
  FDescription = "",
  FModuleId,
}) => {
  const existing = await query(
    "SELECT FId FROM t_permissions WHERE FCode = ? LIMIT 1",
    [FCode]
  );
  if (existing.length > 0) {
    throw { status: 400, message: "权限编码已存在" };
  }

  // 检查模块是否存在
  if (FModuleId) {
    const module = await query(
      "SELECT FId FROM t_permission_modules WHERE FId = ? LIMIT 1",
      [FModuleId]
    );
    if (module.length === 0) {
      throw { status: 400, message: "权限模块不存在" };
    }
  }

  const FId = uuidv4();
  await query(
    "INSERT INTO t_permissions (FId, FName, FCode, FDescription, FModuleId) VALUES (?, ?, ?, ?, ?)",
    [FId, FName, FCode, FDescription, FModuleId]
  );

  return { FId, FName, FCode, FDescription, FModuleId };
};

exports.updatePermission = async (
  id,
  FName,
  FCode,
  FDescription,
  FModuleId
) => {
  const existing = await query(
    "SELECT FId FROM t_permissions WHERE FId = ? LIMIT 1",
    [id]
  );
  console.log(id);

  if (existing.length === 0) {
    throw { status: 500, message: "权限不存在" };
  }

  // 检查模块是否存在
  if (FModuleId) {
    const module = await query(
      "SELECT FId FROM t_permission_modules WHERE FId = ? LIMIT 1",
      [FModuleId]
    );
    if (module.length === 0) {
      throw { status: 400, message: "权限模块不存在" };
    }
  }

  const updates = [];
  const params = [];
  if (FName !== undefined) {
    updates.push("FName = ?");
    params.push(FName);
  }
  if (FCode !== undefined) {
    updates.push("FCode = ?");
    params.push(FCode);
  }
  if (FDescription !== undefined) {
    updates.push("FDescription = ?");
    params.push(FDescription);
  }
  if (FModuleId !== undefined) {
    updates.push("FModuleId = ?");
    params.push(FModuleId);
  }

  if (updates.length === 0) {
    throw { status: 400, message: "无更新内容" };
  }

  params.push(id);
  const result = await query(
    `UPDATE t_permissions SET ${updates.join(", ")} WHERE FId = ?`,
    params
  );

  return result.affectedRows > 0;
};

// 删除权限（事务版）
exports.deletePermission = async (id) => {
  return withTransaction(async (conn) => {
    const roles = await query(
      "SELECT FRoleId FROM t_role_permissions WHERE FPermissionId = ? LIMIT 1",
      [id],
      conn
    );

    if (roles.length > 0) {
      throw { status: 400, message: "该权限仍被角色使用，无法删除" };
    }
    const result = await query(
      "DELETE FROM t_permissions WHERE FId = ?",
      [id],
      conn
    );

    if (result.length === 0) {
      throw { status: 500, message: "权限不存在" };
    }

    return true;
  });
};

/**
 * =========================
 * 角色权限管理
 * =========================
 */

exports.getRolePermissions = async (roleId) => {
  const role = await query("SELECT FId FROM t_roles WHERE FId = ? LIMIT 1", [
    roleId,
  ]);
  if (role.length === 0) {
    throw { status: 500, message: "角色不存在" };
  }

  const permissions = await query(
    `SELECT 
      p.FId, 
      p.FName, 
      p.FCode, 
      pm.FId as FModuleId,
      pm.FName as FModuleName,
      CASE WHEN rp.FRoleId IS NOT NULL THEN 1 ELSE 0 END as FHasPermission
     FROM t_permissions p
     LEFT JOIN t_role_permissions rp ON p.FId = rp.FPermissionId AND rp.FRoleId = ?
     LEFT JOIN t_permission_modules pm ON p.FModuleId = pm.FId
     ORDER BY pm.FOrderNum, p.FCode`,
    [roleId]
  );

  // ✅ 在这里把 0/1 转成 true/false
  const mapped = permissions.map((item) => ({
    ...item,
    FHasPermission: item.FHasPermission === 1,
  }));

  return mapped;
};

// 更新角色权限（事务版）
exports.updateRolePermissions = async (FRoleId, FPermissionIds) => {
  const role = await query("SELECT FId FROM t_roles WHERE FId = ? LIMIT 1", [
    FRoleId,
  ]);

  if (role.length === 0) {
    throw { status: 500, message: "角色不存在" };
  }

  return withTransaction(async (conn) => {
    await query(
      "DELETE FROM t_role_permissions WHERE FRoleId = ?",
      [FRoleId],
      conn
    );

    if (FPermissionIds && FPermissionIds.length > 0) {
      const permissions = await query(
        `SELECT FId FROM t_permissions WHERE FId IN (?)`,
        [FPermissionIds],
        conn
      );
      if (permissions.length !== FPermissionIds.length) {
        throw { status: 400, message: "包含无效的权限ID" };
      }

      const values = FPermissionIds.map((FId) => [FRoleId, FId]);
      await query(
        "INSERT INTO t_role_permissions (FRoleId, FPermissionId) VALUES ?",
        [values],
        conn
      );
    }

    return true;
  });
};

/**
 * =========================
 * 用户角色管理
 * =========================
 */

exports.getUserRoles = async (userId) => {
  const user = await query(
    "SELECT FUserId FROM t_users WHERE FUserId = ? LIMIT 1",
    [userId]
  );
  if (user.length === 0) {
    throw { status: 500, message: "用户不存在" };
  }

  const roles = await query(
    `SELECT r.FId, r.FName, r.FCode, 
     CASE WHEN ur.FUserId IS NOT NULL THEN 1 ELSE 0 END as FHasRole
     FROM t_roles r
     LEFT JOIN t_user_roles ur ON r.FId = ur.FRoleId AND ur.FUserId = ?
     ORDER BY r.FCode`,
    [userId]
  );

  // 转换 1/0 为 true/false
  return roles.map((role) => ({
    ...role,
    FHasRole: !!role.FHasRole, // 1 -> true, 0 -> false
  }));
};

// 更新用户角色（事务版）
exports.updateUserRoles = async (FUserId, FRoleIds) => {
  const user = await query(
    "SELECT FUserId FROM t_users WHERE FUserId = ? LIMIT 1",
    [FUserId]
  );
  if (user.length === 0) {
    throw { status: 500, message: "用户不存在" };
  }

  return withTransaction(async (conn) => {
    await query("DELETE FROM t_user_roles WHERE FUserId = ?", [FUserId], conn);

    if (FRoleIds && FRoleIds.length > 0) {
      const roles = await query(
        `SELECT FId FROM t_roles WHERE FId IN (?)`,
        [FRoleIds],
        conn
      );
      if (roles.length !== FRoleIds.length) {
        throw { status: 400, message: "包含无效的角色ID" };
      }

      const values = FRoleIds.map((FId) => [FUserId, FId]);
      await query(
        "INSERT INTO t_user_roles (FUserId, FRoleId) VALUES ?",
        [values],
        conn
      );
    }

    return true;
  });
};

/**
 * =========================
 * 用户权限管理
 * =========================
 */

/**
 * 获取用户的所有权限（通过角色关联）
 * @param {string} userId - 用户ID
 * @returns {Promise<string[]>} - 权限编码（FCode）数组
 */
exports.getUserPermissions = async (userId) => {
  // 1. 检查用户是否存在
  const user = await query(
    "SELECT FUserId FROM t_users WHERE FUserId = ? LIMIT 1",
    [userId]
  );
  if (user.length === 0) {
    throw { status: 500, message: "用户不存在" };
  }

  // 2. 查询用户的所有角色关联的权限
  const permissions = await query(
    `SELECT DISTINCT p.FCode
     FROM t_permissions p
     JOIN t_role_permissions rp ON p.FId = rp.FPermissionId
     JOIN t_user_roles ur ON rp.FRoleId = ur.FRoleId
     WHERE ur.FUserId = ?`,
    [userId]
  );

  // 3. 返回权限编码数组（如 ['role:add', 'user:edit']）
  return permissions.map(p => p.FCode);
};
